package com.erbao.classloader;

import java.io.*;

/**
 * 打破双亲委派重写loadClass
 * @author CaoBaoYin
 * @since 22/3/24 17:21
 */
public class CustomClassLoader2 extends ClassLoader {
    public CustomClassLoader2() {
    }

    public CustomClassLoader2(ClassLoader parent) {
        super(parent);
    }

    @Override
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        File file = new File("C:\\Users\\by\\IdeaProjects\\SpringBoot\\biz-base\\target\\classes".concat(File.separator).concat(name.replaceAll("\\.", "\\\\")).concat(".class"));
        if (! file.exists()) {
            System.out.println(file.getAbsolutePath());
            // Oject 自己不加载
            return super.loadClass(name, resolve);
        }

        byte[] bytes = null;
        try (FileInputStream fi = new FileInputStream(file);
             ByteArrayOutputStream baos = new ByteArrayOutputStream();) {
            byte[] buffer = new byte[1024];
            int size = 0;
            while ((size = fi.read(buffer)) != -1) {
                baos.write(buffer, 0, size);
            }

            bytes = baos.toByteArray();

            return defineClass(name, bytes, 0, bytes.length);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return super.loadClass(name, resolve);
    }

    public static void main(String[] args) {
        try {
            CustomClassLoader2 customClassLoader1 = new CustomClassLoader2(null);
            Class<?> clazz = customClassLoader1.loadClass("com.erbao.biz.entity.vo.DictVo", false);
            // java.lang.LinkageError: loader (instance of  com/erbao/classloader/CustomClassLoader2): attempted  duplicate class definition for name: "com/erbao/biz/entity/vo/DictVo"
            // Class<?> clazz2 = customClassLoader1.loadClass("com.erbao.biz.entity.vo.DictVo", false);
            // System.out.println(clazz == clazz2);
            Class<?> clazz2 = new CustomClassLoader2(null).loadClass("com.erbao.biz.entity.vo.DictVo", false);
            System.out.println(clazz == clazz2);
            System.out.println(clazz.getName());
            System.out.println(clazz.getClassLoader());
            System.out.println(clazz.getClassLoader().getParent());
            System.out.println(clazz.getClassLoader().getClass().getClassLoader());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }



    }
}
